/*
 *	Implementation of calendar encryption/decryption
 */
 
// some imports
var info = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);

if(info.version.charAt(0)>=5){
Components.utils.import("resource://gre/modules/AddonManager.jsm"); //needed!
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource:///modules/MailUtils.js")
}

//needed when a to promt infowindow when user trys to encrypt an already encrypted event
var stringBundlef;
window.addEventListener("load", function(){
	stringBundlef = document.getElementById("cryptoBirdStringBundle");
}, false); 
 
// variables to see if the content is already encrypted
var startEncryptedContent = "-----BEGIN PGP MESSAGE-----";
var endEncryptedContent = "-----END PGP MESSAGE-----";
var startEncryptedTitel = "-----SUBJECT ENCRYPTED-----";

// temp variables
var decrypted = false;
var event_title;
var event_description;
var plain = false;
var i = 0;

// get the current path of the keyring
var pubringPath = Services.prefs.getCharPref('cryptoBird.pgp_path');
var pubringFile = Services.prefs.getCharPref('cryptoBird.pgp_pk_name');
var secRingFile = Services.prefs.getCharPref('cryptoBird.pgp_sk_name');

// get the email the user is using as the owner of the calendar
const nsIPrefBranch = Components.interfaces.nsIPrefBranch;
const prefB = Components.classes["@mozilla.org/preferences-service;1"].getService(nsIPrefBranch);
var calendarlist = prefB.getCharPref("calendar.list.sortOrder").substr(0,36);

//get the default email, which will be used to encrypt content of calendars
var defaultaccount = prefB.getCharPref("mail.accountmanager.defaultaccount");
var defaultid = prefB.getCharPref("mail.account."+defaultaccount+".identities");
var defaultemail = prefB.getCharPref("mail.identity."+defaultid+".useremail");


// variable contains the emails of users involved in the event, for now just from the default user
var userIDs = new Array();
userIDs[0] = defaultemail;

//for debuging reasons
debug = false;


/*
 *	Prompt for PGP password
 */
function passwd_onload() {
	  var loginManager = Components.classes["@mozilla.org/login-manager;1"]
        .getService(Components.interfaces.nsILoginManager);
		var loginInfo = Components.classes["@mozilla.org/login-manager/loginInfo;1"]
        .createInstance(Components.interfaces.nsILoginInfo);
		
		var logins;
		if (debug) alert('Starting login procedure');
		
		if(loginManager.countLogins('chrome://cryptobird','','cryptobird_pgp_pw') == 0){
			if (debug) alert('No Logins saved');
			var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
			var password = {value: "ThunderSearch"};        // XXX: default the password to ThunderSearch (developing PW)
			var check = {value: true};                   		
			var result = promptService.promptPassword(null, stringBundlef.getString("cryptoBird.main.DBPW"), stringBundlef.getString("cryptoBird.main.DBPWmessage"), password, stringBundlef.getString("cryptoBird.main.DBPWnotask"), check);
			password = password.value;
			
		  if(check.value){
				loginInfo.init('chrome://cryptobird', null, 'cryptobird_pgp_pw', 'pgpdefault', password, "", "");
				loginManager.addLogin(loginInfo);
				if (debug) alert('Login added to DB');
				decryptContent(password)
				}
		}else{
		   if (debug) alert('Found Login');
			//look for pw
			logins = loginManager.findLogins({}, "chrome://cryptobird", null, 'cryptobird_pgp_pw');
			for (var i = 0; i < logins.length; i++) {
					      if (logins[i].username == 'pgpdefault') {
					         password = logins[i].password;
					         result = true;
					         if (debug) alert('Password was found');
					         break;
					      }
			  	
			  }
		  decryptContent(password);	  
	    }
	  	  decryptContent(password);	
}


//different listener added to the window to decide what to do
if(window.addEventListener){
	//check by load if you need to decryptContent
	window.addEventListener("load", passwd_onload, false)
	
	
	//check if you need to encryptContent while closing and saving
	window.addEventListener("close", encryptContent, false)
	
	var menuclose = document.getElementById('item-close-menuitem');
	menuclose.addEventListener("click", encryptContent, false)
	
	var menusaveclose = document.getElementById('item-saveandclose-menuitem');
	menusaveclose.addEventListener("click", encryptContent, false)
	
	var buttonsave = document.getElementById('button-save');
	buttonsave.addEventListener("click", encryptContent, false)
	
	var menusave = document.getElementById('item-save-menuitem');
	menusave.addEventListener("click", encryptContent, false)
}

function decryptContent(passphrase){

	var win = Components.classes["@mozilla.org/appshell/window-mediator;1"].
    getService(Components.interfaces.nsIWindowMediator).
    getMostRecentWindow("mail:3pane");
    
	event_title = document.getElementById('item-title').value;
    event_description = document.getElementById('item-description').value;
    
    //var encod_title = getEncoding(event_title);
    //var encod_desc = getEncoding(event_description);
    
	//myDump(encod_title + "" + encod_desc);
		// check if title is encrypted, if yes then decrypt
		if (event_title.indexOf(startEncryptedTitel) != -1){
			decrypted = true;
			var dec_event_title = win.TheChasingDragon.cryptoBirdJava.decryptCalendarTitel(event_title, passphrase, "UTF-8", pubringPath, secRingFile);
			document.getElementById('item-title').value = dec_event_title;
			refreshTitle();
			document.getElementById('CB_lockIcon').hidden = false;
		}

		// check if content is encrypted, if yes then decrypt
		if (event_description.indexOf(startEncryptedContent) != -1 && event_description.indexOf(endEncryptedContent) != -1) {
	    	decrypted = true;
	    	var dec_event_description = win.TheChasingDragon.cryptoBirdJava.decryptCalendarContent(event_description, passphrase, "UTF-8", pubringPath, secRingFile);
	    	document.getElementById('item-description').value = dec_event_description;
	    	document.getElementById('CB_lockIcon').hidden = false;
		}
	
}

function encryptContent(){
	var win = Components.classes["@mozilla.org/appshell/window-mediator;1"].
    getService(Components.interfaces.nsIWindowMediator).
    getMostRecentWindow("mail:3pane");
    
	event_title = document.getElementById('item-title').value;
    event_description = document.getElementById('item-description').value;
    
	document.getElementById('CB_lockIcon').hidden = false;
	if(decrypted && (plain == false)){
		
		// check if title is encrypted if not, then encrypt
		if (event_title.indexOf(startEncryptedTitel) == -1){
			var enc_event_title = '-----SUBJECT ENCRYPTED-----'+win.TheChasingDragon.cryptoBirdJava.encryptSubject(userIDs, event_title, pubringPath, pubringFile);
			document.getElementById('item-title').value = enc_event_title;
			refreshTitle();
		}
	
		// check if content is encrypted if not, then encrypt
		if (event_description.indexOf(startEncryptedContent) == -1 && event_description.indexOf(endEncryptedContent) == -1) {
	    	var enc_event_description = win.TheChasingDragon.cryptoBirdJava.encryptContent(userIDs, event_description, pubringPath, pubringFile);
	    	document.getElementById('item-description').value = enc_event_description;
		}
		
	}else{
		//save the current values again
		document.getElementById('item-title').value = event_title;
        document.getElementById('item-description').value = event_description;
		
	}
}

function encryptInCalendar(){
	var win = Components.classes["@mozilla.org/appshell/window-mediator;1"].
    getService(Components.interfaces.nsIWindowMediator).
    getMostRecentWindow("mail:3pane");
    
	event_title = document.getElementById('item-title').value;
    event_description = document.getElementById('item-description').value;
	document.getElementById('CB_lockIcon').hidden = false;
	// check if title is encrypted if not, then encrypt
		if (event_title.indexOf(startEncryptedTitel) == -1){
			var enc_event_title = '-----SUBJECT ENCRYPTED-----'+win.TheChasingDragon.cryptoBirdJava.encryptSubject(userIDs, event_title, pubringPath, pubringFile);
			document.getElementById('item-title').value = enc_event_title;
			refreshTitle();
		}
	
		// check if content is encrypted if not, then encrypt
		if (event_description.indexOf(startEncryptedContent) == -1 && event_description.indexOf(endEncryptedContent) == -1) {
	    	var enc_event_description = win.TheChasingDragon.cryptoBirdJava.encryptContent(userIDs, event_description, pubringPath, pubringFile);
	    	document.getElementById('item-description').value = enc_event_description;
		}
}

// check if the user wants to save the event in plain even it was decrypted
function checkCheckBox(){
	
	i = i + 1;
    if(even(i)) {
    	plain = false;
    	
    }else{
        plain = true;
        }
}


// help function which is used by checkCheckBox to see if the user want to save the text in plain
function even(i){
	if(i % 2 == 0){
	 	return true;
	}else {return false;}
}


function onEncEventMenuItemCommand(){
	passwd_onload();
}

function onEncCalendarMenuItemCommand(){
	event_title = document.getElementById('item-title').value;
    event_description = document.getElementById('item-description').value;
	// check if the event/task is already encrypted
	if (event_description.indexOf(startEncryptedContent) != -1 && event_description.indexOf(endEncryptedContent) != -1 && event_title.indexOf(startEncryptedTitel) != -1){
		var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
	    prompts.alert(null, stringBundlef.getString("cryptoBird.compose.infowindowtitle"),stringBundlef.getString("cryptoBird.calendar.infoEncEvent"));
	
	}else{ encryptInCalendar();}
	
}

/**
	 *	Get the Encoding of a message
	 */
	function getEncoding(aMessage) {
		var encoding = aMessage.Charset
		myDump(encoding +" ");
		return encoding;
    };

/**
 * refreshes window title (manual input from user needed, so we send blank and del as keyboard events)
 */
function refreshTitle(){
	sendKeyEvent(32);
	sendKeyEvent(8);
}

/**
 * function needed for workaround to update title of window: this function inserts the character c into the title which causes the window title to change 
 * @param c  the character which should be inserted
 */

function sendKeyEvent(c){
	var e = document.createEvent("KeyboardEvent");
	e.initKeyEvent('keypress', true, true, null, false, false, false, false, c, c);
	
	var obj = document.getElementById("item-title");
	obj.inputField.dispatchEvent(e);
}

function myDump(aMessage) {
	  var consoleService = Components.classes["@mozilla.org/consoleservice;1"]
	                                 .getService(Components.interfaces.nsIConsoleService);
	  consoleService.logStringMessage("CrytoBird: " + aMessage);
}